package com.stefanie.eventlistenerdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: stefanie-zy
 * @time: 2024/1/12-16:04
 * @description: 配置-线程池
 */
@Configuration
@Slf4j
@EnableAsync
public class ThreadPoolConfig {

    @Value("${spring.task.execution.pool.core-size}")
    private int coreSize;
    @Value("${spring.task.execution.pool.max-size}")
    private int maxSize;
    @Value("${spring.task.execution.pool.queue-capacity}")
    private int queueCapacity;
    @Value("${spring.task.execution.thread-name-prefix}")
    private String namePrefix;
    @Value("${spring.task.execution.pool.keep-alive}")
    private int keepAliveSeconds;

    /**
     * @description: AbortPolicy-默认策略（中止策略）新任务提交时直接抛出未检查的异常RejectedExecutionException，该异常可由调用者捕获。
     * CallerRunsPolicy-为调节机制，既不抛弃任务也不抛出异常，而是将某些任务回退到调用者。不会在线程池的线程中执行新的任务，而是在调用exector的线程中运行新的任务。
     * DiscardPolicy-丢弃策略，丢弃队列尾部的任务请求，即丢弃最新进来的任务请求。
     * DiscardOldestPolicy-丢弃策略，丢弃队列头部的任务请求，即丢弃最老进来的任务请求。
     */

    @Bean(name = "stefanieExecutor")
    public ThreadPoolTaskExecutor stefanieExecutor() {
        log.info("Start creating a thread pool ");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(maxSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(namePrefix);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        //线程初始化
        executor.initialize();
        return executor;
    }

}
